package com.example.patient.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.example.common.entity.*;
import com.example.common.enums.PayType;
import com.example.common.support.ApiException;
import com.example.common.support.Result;
import com.example.common.support.ResultCode;
import com.example.common.utils.CheckUtils;
import com.example.common.utils.IdUtils;
import com.example.common.utils.UIDUtils;
import com.example.patient.dto.req.*;
import com.example.patient.dto.resp.*;
import com.example.patient.feign.FileFeign;
import com.example.patient.jpa.*;
import com.example.patient.mapper.InquiryMapper;
import com.example.patient.properties.WxProp;
import com.example.patient.service.InquiryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author wxy
 * @Date 2021/1/18 11:33
 * @Version 1.0
 */
@Service
public class InquiryServiceImpl implements InquiryService {
    @Resource
    private UIDUtils uidUtils;
    @Resource
    private FileFeign fileFeign;
    @Resource
    private WxProp wxProp;

    @Resource
    private InquiryMapper inquiryMapper;

    @Resource
    private PatientsInfoRepository patientsInfoRepository;
    @Resource
    private OnlineConsultationRepository onlineConsultationRepository;
    @Resource
    private OrderMainRepository orderMainRepository;
    @Resource
    private CommentRepository commentRepository;
    @Resource
    private DoctorBaseInfoRepository doctorBaseInfoRepository;
    @Resource
    private ImgRepository imgRepository;
    @Resource
    private ConsultationLogRepository consultationLogRepository;
    @Resource
    private RxMainRepository rxMainRepository;
    @Resource
    private RxInfoRepository rxInfoRepository;
    @Resource
    private LogisticsDRepository logisticsDRepository;
    @Resource
    private RxDrugsRepository rxDrugsRepository;
    @Resource
    private DiseaseInfoRepository diseaseInfoRepository;
    @Resource
    private HospitalRepository hospitalRepository;
    @Resource
    private AddressRepository addressRepository;
    @Resource
    private ExInfoRepository exInfoRepository;

    /**
     * 问诊列表
     */
    @Override
    public List<IMListResp> IMList() {
        Long uid = uidUtils.getUid();
        List<IMListResp> dataList = inquiryMapper.cReceive(uid);
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }

        List<Long> ocIds = dataList.stream().map(IMListResp::getOcId).collect(Collectors.toList());
        List<ConsultationLog> consultationLogList = inquiryMapper.iMConsultationLog(ocIds);

        if (CollectionUtils.isEmpty(consultationLogList)) {
            dataList = dataList.stream().peek(p -> {
                p.setCType(0);
                p.setImContent("");
                p.setLastTime(0L);
            }).sorted(Comparator.comparing(IMListResp::getLastTime)).collect(Collectors.toList());
            return dataList;
        } else {
            dataList = dataList.stream().peek(p -> {
                ConsultationLog consultationLog = consultationLogList.stream()
                        .filter(f -> f.getOcId().equals(p.getOcId())).findFirst().orElse(null);
                if (!ObjectUtils.isEmpty(consultationLog)) {
                    p.setCType(consultationLog.getCType());
                    p.setImContent(consultationLog.getImContent());
                    p.setLastTime(consultationLog.getCreateTime().getTime());
                }
            }).collect(Collectors.toList());
        }
        return dataList;
    }

    /**
     * 未接诊列表
     */
    @Override
    public List<NoReceiveListResp> NoReceiveList() {
        Long uid = uidUtils.getUid();
        List<NoReceiveListResp> dataList = inquiryMapper.cNoReceive(uid);
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }
        dataList = dataList.stream().peek(p -> {
            DateTime dateTime = DateUtil.offsetMinute(p.getOrderPayTime(), p.getToBeReceive());
            Long lastTime = DateUtil.between(dateTime, new Date(), DateUnit.SECOND);
            p.setLastTime(lastTime);
        }).collect(Collectors.toList());
        return dataList;
    }

    /**
     * 问诊 就诊 患者基础信息
     */
    @Override
    public PatientsResp Patients(PatientsReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String orderNo = CheckUtils.checkNullReturn(req.getOrderNO(), new ApiException(1, "订单号不能为空"));

        PatientsInfo patientsInfo = patientsInfoRepository.findFirstByOrderNo(orderNo);
        CheckUtils.checkNull(patientsInfo, new ApiException(1, "未查询到数据"));
        OnlineConsultation onlineConsultation = onlineConsultationRepository.findFirstByOrderNo(orderNo);
        CheckUtils.checkNull(onlineConsultation, new ApiException(1, "未查询到数据"));
        OrderMain orderMain = orderMainRepository.findById(orderNo).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        Comment comment = commentRepository.findById(orderNo).orElse(null);
        DoctorBaseInfo doctorBaseInfo = doctorBaseInfoRepository.findById(onlineConsultation.getDcId())
                .orElseThrow(() -> new ApiException(1, "未查询到数据"));

        PatientsResp resp = new PatientsResp();
        resp.setHxId(doctorBaseInfo.getHxId());
        resp.setHead(doctorBaseInfo.getHead());
        resp.setDocName(doctorBaseInfo.getName());
        resp.setPid(patientsInfo.getPid());
        resp.setName(patientsInfo.getName());
        resp.setSex(patientsInfo.getSex());
        resp.setAge(patientsInfo.getAge());
        resp.setFirst(patientsInfo.getFirst());
        resp.setChiefComplaint(patientsInfo.getChiefComplaint());
        resp.setAType(orderMain.getAType());
        resp.setOcId(orderMain.getOcId());
        resp.setImStartTime(onlineConsultation.getStartTime().getTime());
        resp.setImEndTime(1 == onlineConsultation.getOcStatus() ? onlineConsultation.getEndTime().getTime()
                : onlineConsultation.getFactFinishTime().getTime());
        resp.setImLave(
                DateUtil.between(onlineConsultation.getEndTime(), onlineConsultation.getStartTime(), DateUnit.HOUR));
        resp.setIsComment(null == comment ? Boolean.FALSE : Boolean.TRUE);
        return resp;
    }
    
    @Override
    public Boolean saveTongueImg(String OrderNO, String TongueImg){
        PatientsInfo info = patientsInfoRepository.findFirstByOrderNo(OrderNO);
        info.setTongueImg(TongueImg);
        try {
            patientsInfoRepository.save(info);
            return true;
        } catch (Exception e) {
            //TODO: handle exception
        }
        return false;
    }

    /**
     * 就诊详情（非本院首诊）
     */
    @Override
    public DiagnosisOutResp DiagnosisOut(DiagnosisOutReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String orderNo = CheckUtils.checkNullReturn(req.getOrderNO(), new ApiException(1, "订单号不能为空"));

        PatientsInfo patientsInfo = patientsInfoRepository.findFirstByOrderNo(orderNo);
        CheckUtils.checkNull(patientsInfo, new ApiException(1, "未查询到数据"));

        List<String> images = imgRepository.findByPatientsInfoId(patientsInfo.getId()).stream().map(Img::getImg)
                .collect(Collectors.toList());

        DiagnosisOutResp resp = new DiagnosisOutResp();
        resp.setName(patientsInfo.getName());
        resp.setSex(patientsInfo.getSex());
        resp.setAge(patientsInfo.getAge());
        resp.setAType(patientsInfo.getAType());
        resp.setChiefComplaint(patientsInfo.getChiefComplaint());
        resp.setAllergy(patientsInfo.getAllergy());
        resp.setPastDisease(patientsInfo.getPastDisease());
        resp.setFVisitDate(DateUtil.formatDate(patientsInfo.getFVisitDate()));
        resp.setFHospital(patientsInfo.getFHospital());
        resp.setFDepartment(patientsInfo.getFDepartment());
        resp.setFDiagnosis(patientsInfo.getFDiagnosis());
        resp.setImages(images);
        return resp;
    }

    /**
     * 问诊 就诊 对话记录
     */
    @Override
    public PageInfo<IMLogListResp> IMLogList(IMLogListReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Long ocId = CheckUtils.checkNullReturn(req.getOCID(), new ApiException(1, "会话标识不能为空"));
        Integer pageNumber = CheckUtils.checkNullReturn(req.getPage(), new ApiException(1, "分页页数不能为空"));
        Integer pageSize = CheckUtils.checkNullReturn(req.getLimit(), new ApiException(1, "分页条数不能为空"));

        PageInfo<IMLogListResp> page = PageHelper.startPage(pageNumber, pageSize).doSelectPageInfo(() -> inquiryMapper.IMLogList(ocId));
        List<IMLogListResp> list =   page.getList();
        list = list.stream().sorted(Comparator.comparing(IMLogListResp::getCreateTime)).collect(Collectors.toList());
        page.setList(list);
        return page;
    }

    /**
     * 问诊 就诊 记录对话
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public Boolean IMSave(IMSaveReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        Long ocId = CheckUtils.checkNullReturn(req.getOCID(), new ApiException(1, "会话标识不能为空"));
        String fromHx = CheckUtils.checkNullReturn(req.getFromHX(), new ApiException(1, "发送人ID不能为空"));
        String toHx = CheckUtils.checkNullReturn(req.getToHX(), new ApiException(1, "接收人ID不能为空"));
        String imContent = CheckUtils.checkNullReturn(req.getIMContent(), new ApiException(1, "内容不能为空"));
        Integer cType = CheckUtils.checkNullReturn(req.getCType(), new ApiException(1, "类型不能为空"));

        ConsultationLog consultationLog = new ConsultationLog();
        consultationLog.setId(IdUtils.generateId());
        consultationLog.setOcId(ocId);
        consultationLog.setImType(1);
        consultationLog.setFromHx(fromHx);
        consultationLog.setToHx(toHx);
        consultationLog.setCreateTime(new Date());
        consultationLog.setImContent(imContent);
        consultationLog.setHaveRead(Boolean.FALSE);
        consultationLog.setCType(cType);
        consultationLog.setDType(req.getDType());
        consultationLog.setRxOrderNo(req.getRxOrderNO());
        consultationLogRepository.save(consultationLog);

        return Boolean.TRUE;
    }

    /**
     * 问诊 就诊 上传对话文件
     */
    @Override
    public Object IMUpLoad(MultipartFile file) {
        CheckUtils.checkNull(file, new ApiException(1, "文件不能为空"));
        Result<Object> result = fileFeign.updateFile(file);
        if (result.getCode()== ResultCode.DOWNGRADE.getCode()){
            throw new ApiException(ResultCode.DOWNGRADE.getCode(),"文件上传服务降级");
        }
        return result.getData();
    }

    /**
     * 问诊 就诊 中药处方信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public ZRxDetailResp ZRxDetail(ZRxDetailReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String rxOrderNO = CheckUtils.checkNullReturn(req.getRxOrderNO(), new ApiException(1, "处方订单id不能为空"));

        Map<String, Object> dataMap = inquiryMapper.ZRxDetail(rxOrderNO);
        CheckUtils.checkNull(dataMap, new ApiException(1, "未查询到数据"));

        RxMain rxMain = rxMainRepository.findById(rxOrderNO).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        RxInfo rxInfo = rxInfoRepository.findById(rxOrderNO).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        String dialectical = rxMain.getDialectical();
        Boolean isHandle = logisticsDRepository.countByOrderNoAndOrderType(rxOrderNO, 1) > 0 ? Boolean.TRUE
                : Boolean.FALSE;
        List<Long> disIds = Arrays.stream(rxMain.getDisIds().split(",")).map(Long::parseLong)
                .collect(Collectors.toList());
        StringBuilder sb = new StringBuilder();
        diseaseInfoRepository.findByIdIn(disIds).stream()
                .map(m -> m.getCode() + " " + m.getDiseaseName()).forEach(m -> {
            sb.append(m);
        });
        Boolean isRxExpired = Boolean.TRUE;
        if (rxMain.getSystemStatus() != 1) {
            isRxExpired = Boolean.FALSE;
        }
        DateTime dateTime = DateUtil.offsetDay(rxMain.getCreateTime(), 2);
        if (dateTime.isAfterOrEquals(new Date())) {
            isRxExpired = Boolean.FALSE;
        }
        if (isRxExpired) {
            rxMain.setSystemStatus(3);
            rxMainRepository.save(rxMain);
        }

        ZRxDetailResp resp = new ZRxDetailResp();
        resp.setName(null == dataMap.get("Name") ? null : dataMap.get("Name").toString());
        resp.setRxOrderNO(null == dataMap.get("RxOrderNO") ? null : dataMap.get("RxOrderNO").toString());
        resp.setSex(null == dataMap.get("Sex") ? null : dataMap.get("Sex").toString());
        resp.setAge(null == dataMap.get("Age") ? null : Integer.valueOf(dataMap.get("Age").toString()));
        resp.setDepName(null == dataMap.get("depName") ? null : dataMap.get("depName").toString());
        resp.setCreateTime(
                null == dataMap.get("CreateTime") ? null : DateUtil.formatDateTime((Date) dataMap.get("CreateTime")));
        resp.setDialectical(sb.toString());
        resp.setZDialectical(rxMain.getZDialectical());
        resp.setZDialectics(rxMain.getZDialectics());
        resp.setSalePrice(rxMain.getSalePrice());
        resp.setBadge(rxMain.getBadge());
        resp.setOpenDoctor(rxMain.getOpenDoctor());
        resp.setChkStatus(rxMain.getChkStatus());
        resp.setChkDoctor(rxMain.getChkDoctor());
        resp.setFailureReason(rxMain.getFailureReason());
        resp.setFailureRemark(rxMain.getFailureRemark());
        resp.setDialecticalRemark(rxMain.getDialecticalRemark());
        resp.setAVoid(rxInfo.getAvoid());
        resp.setMedTime(rxInfo.getUseTime());
        resp.setDrugInfo(rxInfo.getDrugInfo());
        resp.setTotalDoes(rxInfo.getTotalDoes());
        resp.setDayCount(rxInfo.getDayCount());
        resp.setDoes(rxInfo.getDoes());
        resp.setMedWay(rxInfo.getMedWay());
        resp.setIsHandle(isHandle);
        resp.setIsRxExpired(isRxExpired);
        resp.setZDisCode(rxMain.getZDisCode());
        return resp;
    }

    /**
     * 问诊 就诊 西药处方信息
     */
    @Override
    public XRxDetailResp XRxDetail(XRxDetailReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String rxOrderNO = CheckUtils.checkNullReturn(req.getRxOrderNO(), new ApiException(1, "处方订单NO不能为空"));

        Map<String, Object> dataMap = inquiryMapper.ZRxDetail(rxOrderNO);
        CheckUtils.checkNull(dataMap, new ApiException(1, "未查询到数据"));

        RxMain rxMain = rxMainRepository.findById(rxOrderNO).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        
        List<String> dialectical = new ArrayList<>();
        dialectical.add(rxMain.getDialectical());
        List<Long> disIds = Arrays.stream(rxMain.getDisIds().split(",")).map(Long::parseLong)
                .collect(Collectors.toList());
        StringBuilder sb = new StringBuilder();
        diseaseInfoRepository.findByIdIn(disIds).stream()
                .map(m -> m.getCode() + " " + m.getDiseaseName()).forEach(m -> {
            sb.append(m);
        });

        Boolean isHandle;
        Long count = logisticsDRepository.countByOrderNoAndOrderType(rxOrderNO, 1);
        if (count > 0L) {
            isHandle = Boolean.TRUE;
        } else {
            isHandle = Boolean.FALSE;
        }

        Boolean isRxExpired = Boolean.TRUE;
        DateTime dateTime = DateUtil.offsetDay(rxMain.getCreateTime(), 2);
        if (dateTime.isAfterOrEquals(new Date())) {
            isRxExpired = Boolean.FALSE;
        }
        if (rxMain.getSystemStatus() != 1) {
            isRxExpired = Boolean.FALSE;
        }
        if (isRxExpired) {
            rxMain.setSystemStatus(3);
            rxMainRepository.save(rxMain);
        }

        List<RxDrugs> rxDrugsList = rxDrugsRepository.findByRxOrderNo(rxOrderNO);
        List<XRxDetailResp.RxDrugsResp> rxDrugs = rxDrugsList.stream().map(m -> {
            String suggest = m.getMedWay() + "；每日" + m.getFreq() + "；" + m.getDoes() + m.getDoesUnit() + "/次；"
                    + m.getDay() + "天";
            XRxDetailResp.RxDrugsResp resp = new XRxDetailResp.RxDrugsResp();
            resp.setDrugName(m.getDrugName());
            resp.setNum(m.getNum());
            resp.setRemark(m.getRemark());
            resp.setSpec(m.getSpec());
            resp.setSuggest(suggest);
            return resp;
        }).collect(Collectors.toList());

        XRxDetailResp resp = new XRxDetailResp();
        resp.setRxOrderNO(null == dataMap.get("RxOrderNO") ? null : dataMap.get("RxOrderNO").toString());
        resp.setName(null == dataMap.get("Name") ? null : dataMap.get("Name").toString());
        resp.setAge(null == dataMap.get("Age") ? null : Integer.valueOf(dataMap.get("Age").toString()));
        resp.setSex(null == dataMap.get("Sex") ? null : dataMap.get("Sex").toString());
        resp.setDepName(null == dataMap.get("depName") ? null : dataMap.get("depName").toString());
        resp.setCreateTime(
                null == dataMap.get("CreateTime") ? null : DateUtil.formatDateTime((Date) dataMap.get("CreateTime")));
        resp.setDialectical(sb.toString());
        resp.setRxDrugs(rxDrugs);
        resp.setSalePrice(rxMain.getSalePrice());
        resp.setBadge(rxMain.getBadge());
        resp.setOpenDoctor(rxMain.getOpenDoctor());
        resp.setIsRecipeDocCa(rxMain.getIsRecipeDocCa());
        resp.setChkDoctor(rxMain.getChkDoctor());
        resp.setChkStatus(rxMain.getChkStatus());
        resp.setFailureReason(rxMain.getFailureReason());
        resp.setFailureRemark(rxMain.getFailureRemark());
        resp.setIsHandle(isHandle);
        resp.setIsRxExpired(isRxExpired);
        if(rxMain.getDType() == 3){
            resp.setZDialectical(rxMain.getZDialectical());
            resp.setZDialectics(rxMain.getZDialectics());   
        }
        return resp;
    }

    /**
     * 处方信息结算
     */
    @Override
    public RxOrderSettlementResp RxOrderSettlement(RxOrderSettlementReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String rxOrderNO = CheckUtils.checkNullReturn(req.getRxOrderNO(), new ApiException(1, "处方订单NO不能为空"));
        Long aid = CheckUtils.checkNullReturn(req.getAid(), new ApiException(1, "aid不能为空"));

        Long uid = uidUtils.getUid();

        Address address = inquiryMapper.ClientAddressDynamic(uid, aid);
        if (ObjectUtils.isEmpty(address)) {
            address = inquiryMapper.ClientAddress(uid);
        }
        RxOrderSettlementResp resp = new RxOrderSettlementResp();
        
            
        if(address != null){
        RxOrderSettlementResp.AddressResp addressResp = new RxOrderSettlementResp.AddressResp();
        addressResp.setId(address.getId());
        addressResp.setClientId(address.getClientId());
        addressResp.setCName(address.getCName());
        addressResp.setCPhone(address.getCPhone());
        addressResp.setCDetail(address.getCDetail());
        addressResp.setCAddress(address.getCAddress());
        addressResp.setDefaultBit(address.getDefaultBit());
        addressResp.setArea(address.getArea());
        resp.setAddress(addressResp);
    }

        Hospital hospital = hospitalRepository.findFirstByOrderByIdDesc();
        CheckUtils.checkNull(hospital, new ApiException(1, "未查询到数据"));
        RxOrderSettlementResp.SelfResp selfResp = new RxOrderSettlementResp.SelfResp();
        selfResp.setIco(hospital.getIco());
        selfResp.setSelfAddress(hospital.getSelfAddress());
        selfResp.setSelfName(hospital.getSelfName());

        List<Map<String, Object>> mapList = inquiryMapper.RxOrderSettlementRespDrugListResp(rxOrderNO);
        List<RxOrderSettlementResp.DrugListResp> drugList = mapList.stream().map(m -> {
            RxOrderSettlementResp.DrugListResp dresp = new RxOrderSettlementResp.DrugListResp();
            dresp.setDrugName(null == m.get("DrugName") ? null : (String) m.get("DrugName"));
            dresp.setImg(null == m.get("Img") ? null : (String) m.get("Img"));
            dresp.setNum(null == m.get("Num") ? null : (Integer) m.get("Num"));
            dresp.setPrice(null == m.get("Price") ? null : (BigDecimal) m.get("Price"));
            dresp.setSpec(null == m.get("Spec") ? null : (String) m.get("Spec"));
            return dresp;
        }).collect(Collectors.toList());

        Map<String, Object> map = inquiryMapper.RxOrderSettlementRespDocInfoResp(rxOrderNO);
        CheckUtils.checkNull(map, new ApiException(1, "未查询到数据"));
        RxOrderSettlementResp.DocInfoResp docInfoResp = new RxOrderSettlementResp.DocInfoResp();
        docInfoResp.setDepName(null == map.get("depName") ? null : (String) map.get("depName"));
        docInfoResp.setDType(null == map.get("DType") ? null : map.get("DType").toString());
        docInfoResp.setHead(null == map.get("Head") ? null : (String) map.get("Head"));
        docInfoResp.setName(null == map.get("Name") ? null : (String) map.get("Name"));
        docInfoResp.setTitle(null == map.get("Title") ? null : (String) map.get("Title"));

        BigDecimal drugPriceSum = drugList.stream().map(m -> m.getPrice().multiply(new BigDecimal(m.getNum())))
                .reduce(BigDecimal::add).orElse(new BigDecimal(0));

        
        resp.setSelf(selfResp);
        resp.setDrugList(drugList);
        resp.setDocInfo(docInfoResp);
        resp.setDrugPriceSum(drugPriceSum);
        resp.setFreight(new BigDecimal("0.01"));
        return resp;
    }

    /**
     * 处方确认购买
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public Object RxOrderBuy(RxOrderBuyReq req) {    
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String rxOrderNO = CheckUtils.checkNullReturn(req.getRxOrderNO(), new ApiException(1, "处方订单NO不能为空"));
        Long aid = CheckUtils.checkNullReturn(req.getAid(), new ApiException(1, "aid不能为空"));
        Integer lType = CheckUtils.checkNullReturn(req.getLType(), new ApiException(1, "LType不能为空"));
        Integer payType = CheckUtils.checkNullReturn(req.getPayType(), new ApiException(1, "PayType不能为空"));

        RxMain rxMain = rxMainRepository.findById(rxOrderNO).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        rxMain.setPayType(payType);
        if (lType == 1) {
            rxMain.setFreight(new BigDecimal("0.01"));
            rxMain.setSalePrice(rxMain.getSalePrice().add(new BigDecimal("0.01")));
        }
        rxMainRepository.save(rxMain);

        LogisticsD logistics = new LogisticsD();
        logistics.setOrderNo(rxMain.getRxOrderNO());
        logistics.setLType(lType);
        logistics.setOrderType(1);
        if (lType == 1) {
            Address address = addressRepository.findById(aid).orElseThrow(() -> new ApiException(1, "未查询到数据"));
            logistics.setName(address.getCName());
            logistics.setTel(address.getCPhone());
            logistics.setAddress(address.getCAddress());
            logistics.setIsSend(Boolean.FALSE);
        } else {
            Date date = new Date();         
            SimpleDateFormat sdf =new SimpleDateFormat("yyyy MMdd");
            String str = sdf.format(date);
            logistics.setName("");
            logistics.setTel("");
            logistics.setAddress("");
            logistics.setIsSend(Boolean.TRUE);
            logistics.setSendTime(date);   
            logistics.setWaybill(CreateCode(str));
        }
        logistics.setIsArrive(false);
        logisticsDRepository.save(logistics);

        return String.format(wxProp.getPayUrl(), rxMain.getRxOrderNO(), 2);
    }

    private String CreateCode(String code){
        String stro = logisticsDRepository.findMaxWaybill(code);
        int num = 0;
        if(stro != null && !stro.isEmpty())
            num = new Integer(stro.substring(10).replaceAll("^(0+)", ""));
        if(num >= 9999)
            return "";
        String c = code + " " + padLeft("" + (num + 1), 4, '0');
        if(logisticsDRepository.countByWaybill(c) > 1)
            CreateCode(code);
        return c;
    }

    private String padLeft(String src, int len, char ch) {
        int diff = len - src.length();
        if (diff <= 0) {
            return src;
        }

        char[] charr = new char[len];
        System.arraycopy(src.toCharArray(), 0, charr, diff, src.length());
        for (int i = 0; i < diff; i++) {
            charr[i] = ch;
        }
        return new String(charr);
    }
    /**
     * 支付完成
     */
    @Override
    public InquiryPayCompletionResp PayCompletion(PayCompletionReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String rxOrderNO = CheckUtils.checkNullReturn(req.getRxOrderNO(), new ApiException(1, "处方订单NO不能为空"));

        RxMain rxMain = rxMainRepository.findById(rxOrderNO).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        Boolean isPay = !StringUtils.isEmpty(rxMain.getTransactionID()) ? Boolean.TRUE : Boolean.FALSE;
        LogisticsD logistics = logisticsDRepository.findById(rxOrderNO)
                .orElseThrow(() -> new ApiException(1, "未查询到数据"));

        InquiryPayCompletionResp.SelfResp selfResp = new InquiryPayCompletionResp.SelfResp();
        if (logistics.getLType() == 0) {
            Hospital hospital = hospitalRepository.findFirstByOrderByIdDesc();
            CheckUtils.checkNull(hospital, new ApiException(1, "未查询到数据"));
            selfResp.setSelfAddress(hospital.getSelfAddress());
            selfResp.setSelfName(hospital.getSelfName());
            selfResp.setCode(logistics.getWaybill());
        }

        InquiryPayCompletionResp resp = new InquiryPayCompletionResp();
        resp.setIsPay(isPay);
        resp.setLType(logistics.getLType());
        resp.setOrderNO(rxMain.getOrderNO());
        resp.setPayPrice(rxMain.getSalePrice());
        resp.setPayTime(rxMain.getOrderPayTime());
        resp.setPayTypeName(PayType.valueToDesc(rxMain.getPayType()));
        resp.setSelf(selfResp);
        return resp;
    }

    /**
     * 问诊评价信息
     */
    @Override
    public CommentInfoResp CommentInfo(CommentInfoReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String orderNO = CheckUtils.checkNullReturn(req.getOrderNO(), new ApiException(1, "订单NO不能为空"));

        Hospital hospital = hospitalRepository.findFirstByOrderByIdDesc();
        CheckUtils.checkNull(hospital, new ApiException(1, "未查询到数据"));
        CommentInfoResp.HospitalResp hospitalResp = new CommentInfoResp.HospitalResp();
        hospitalResp.setName(hospital.getName());
        hospitalResp.setIco(hospital.getIco());

        CommentInfoResp.CInfoResp cInfoResp = null;
        Comment comment = commentRepository.findById(orderNO).orElse(null);
        if (!ObjectUtils.isEmpty(comment)) {
            cInfoResp = new CommentInfoResp.CInfoResp();
            cInfoResp.setDRemark(comment.getDRemark());
            cInfoResp.setDScore(comment.getScore());
            cInfoResp.setHRemark(comment.getHRemark());
            cInfoResp.setHScore(comment.getHScore());
            cInfoResp.setSScore(comment.getSScore());
            cInfoResp.setSRemark(comment.getSRemark());
        }

        Map<String, Object> map = inquiryMapper.CommentInfoRespDocInfoResp(orderNO);
        CheckUtils.checkNull(map, new ApiException(1, "未查询到数据"));
        CommentInfoResp.DocInfoResp docInfoResp = new CommentInfoResp.DocInfoResp();
        docInfoResp.setHead(null == map.get("Head") ? null : (String) map.get("Head"));
        docInfoResp.setDepName(null == map.get("depName") ? null : (String) map.get("depName"));
        docInfoResp.setName(null == map.get("Name") ? null : (String) map.get("Name"));
        docInfoResp.setTitle(null == map.get("Title") ? null : (String) map.get("Title"));

        CommentInfoResp resp = new CommentInfoResp();
        resp.setHospital(hospitalResp);
        resp.setCInfo(cInfoResp);
        resp.setDocInfo(docInfoResp);
        return resp;
    }

    /**
     * 完成问诊评价
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "jpaTransactionManager")
    public Object SubmitComment(SubmitCommentReq req) {
        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        String orderNo = CheckUtils.checkNullReturn(req.getOrderNO(), new ApiException(1, "订单NO不能为空"));
        BigDecimal hScore = CheckUtils.checkNullReturn(req.getHScore(), new ApiException(1, "hScore不能为空"));
        String hRemark = CheckUtils.checkNullReturn(req.getHRemark(), new ApiException(1, "hRemark不能为空"));
        BigDecimal dScore = CheckUtils.checkNullReturn(req.getDScore(), new ApiException(1, "dScore不能为空"));
        String dRemark = CheckUtils.checkNullReturn(req.getDRemark(), new ApiException(1, "dRemark不能为空"));

        OrderMain orderMain = orderMainRepository.findById(orderNo).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        Comment comment = commentRepository.findById(orderNo).orElse(null);
        if (null != comment) {
            throw new ApiException(1, "订单重复评价");
        }
        Date date = new Date();
        comment = new Comment();
        comment.setOrderNo(orderNo);
        comment.setHScore(hScore);
        comment.setHRemark(hRemark);
        comment.setScore(dScore);
        comment.setDRemark(dRemark);
        comment.setSScore(req.getSScore());
        comment.setSRemark(req.getSRemark());
        comment.setDcId(orderMain.getDcId());
        comment.setPid(orderMain.getPid());
        comment.setCreateTime(date);
        comment.setIsComment(Boolean.FALSE);
        comment.setTimeOut(date);
        commentRepository.save(comment);

        ExInfo exInfo = exInfoRepository.findById(orderMain.getDcId()).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        long gCount = commentRepository.countByDcIdAndScoreGreaterThanEqual(orderMain.getDcId(), new BigDecimal("4"));
        long count = commentRepository.countByDcId(orderMain.getDcId());
        //todo 计数修改
/*        if (dScore.compareTo(new BigDecimal("4")) > -1) {
            gCount++;
        }*/
        BigDecimal decimal = new BigDecimal(gCount)
                .multiply(new BigDecimal("100.00").divide(new BigDecimal(count), 2, BigDecimal.ROUND_DOWN));
        exInfo.setPraise(decimal);
        exInfoRepository.save(exInfo);
        return null;
    }
}
